﻿using Application.DTO.Tasks;
using Application.IAppService;
using Core.Domain.Tasks;
using Core.Domain.Users;
using Core.Domain.Users.Events;
using Core.EventBus;
using Core.Extensions;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Threading.Tasks;
using Web.EntityFramework;
using Web.EntityFramework.Uow;

namespace Application.AppService
{
    public class TaskAppService:ApplicationService,ITaskAppService
    {
        private readonly IRepository<Core.Domain.Tasks.Task> _taskRepository;
        private readonly IRepository<User> _userRepository;
        public TaskAppService(IUnitOfWork uow,IRepository<Core.Domain.Tasks.Task> taskRepositoy,IRepository<User> userRepository):base(uow)
        {
            _taskRepository = taskRepositoy;
            _userRepository = userRepository;
        }

        public async Task<List<TaskListOutput>> GetAll(TaskListInput input)
        {
            var tasks = await _taskRepository.GetAll().WhereIf(input?.State!=null,m=>m.State==input.State).ToListAsync();
            return Mapper.Map<List<TaskListOutput>>(tasks);
        }


        /// <summary>
        /// finish task,set bonus,the highest limited bonus is 50000 yuan,set the bonus 1000 when the task bonus is 0.
        /// 设置完成任务,分配奖金. 完成人员最高累计获取5w,任务奖励为0时默认设置为1000
        /// </summary>
        /// <param name="taskid"></param>
        /// <returns></returns>
        public async System.Threading.Tasks.Task FinishTask(int taskid)
        {
            Core.Domain.Tasks.Task t = await _taskRepository.Find(taskid);
            if (t != null && t.State!=TaskState.Completed)
            {
                //int userid = t?.AssignedPersonId ?? 0;
                User user=null;
                if ((t.AssignedPersonId ?? 0 )> 0)
                {
                    user = await _userRepository.Find(t.AssignedPersonId);
                    if (user != null)
                    {
                        TaskDomainManager tdm = new TaskDomainManager();
                        tdm.ConfirmBonus(t,user);
                    }
                }
                t.State = TaskState.Completed;

                //just for test
                //should change the user in ConfirmBonus function,eventbus just for non-strong-related logic               
                if (user !=null && t.Bonus > 0)
                {
                    TEventBus.Publish(new FinishTaskEvent()
                    {
                        Bonus = t.Bonus,
                        FinishUser = user
                    });
                }
                await SaveChangesAsync();
            }
        }
    }
}
